package custom.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import custom.security.browser.support.RequireFailedResponse;
import custom.security.core.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by wgt on 2017/10/14.
 */
@Slf4j
@Component
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        AuthenticationException e) throws IOException, ServletException {

        log.info("user login failed ");
        if (AuthenticationConstant.RESPONSE_TYPE_JSON.equals(securityProperties.getBrowser().getResponseType())) {
            httpServletResponse.setStatus(HttpStatus.NOT_IMPLEMENTED.value());
            httpServletResponse.setContentType(AuthenticationConstant.CONTENT_TYPE_APPLICATION_JSON);
            httpServletResponse.getWriter().write(objectMapper.writeValueAsString(new RequireFailedResponse(e.getMessage())));
            return;
        }
        super.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
    }

}
